package com.ossjk.qlh.system.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.ossjk.core.util.CommonUtil;
import com.ossjk.qlh.system.entity.Department;
import com.ossjk.qlh.system.entity.Permission;
import com.ossjk.qlh.system.mapper.PermissionMapper;
import com.ossjk.qlh.system.service.IPermissionService;

/**
 * <p>
 * 权限表 服务实现类
 * </p>
 *
 * @author chair
 * @since 2020-03-21
 */
@Service
public class PermissionServiceImpl extends ServiceImpl<PermissionMapper, Permission> implements IPermissionService {
	@Override
	public boolean removeChildrenById(Serializable id) {
		List<Permission> permissions = queryChildrenById(id);
		QueryWrapper<Department> queryWrapper = new QueryWrapper();
		List<Serializable> ids = new ArrayList<Serializable>();
		for (Permission permission : permissions) {
			ids.add(permission.getId());
		}
		return SqlHelper.retBool(baseMapper.deleteBatchIds(ids));
	}

	/**
	 * 查找所有子节点（包含自身）
	 * 
	 * @param id
	 * @return
	 */
	public List<Permission> queryChildrenById(Serializable id) {
		List<Permission> permissions = null;
		Permission permission = baseMapper.selectById(id);
		if (!CommonUtil.isBlank(permission)) {
			permissions = new ArrayList();
			permissions.add(permission);
			queryChildrenByPid(permission.getId(), permissions);

		}
		return permissions;
	}

	/**
	 * 查找所有子节点（不包含自身）
	 * 
	 * @param pid
	 * @param parent
	 * @return
	 */
	public List<Permission> queryChildrenByPid(Serializable pid, List<Permission> parent) {
		if (CommonUtil.isBlank(parent)) {
			parent = new ArrayList<Permission>();
		}
		QueryWrapper<Permission> queryWrapper = new QueryWrapper();
		List<Permission> children = baseMapper.selectList(queryWrapper.eq("pid", pid));
		if (!CommonUtil.isBlank(children)) {
			parent.addAll(children);
			for (Permission permission : children) {
				queryChildrenByPid(permission.getId(), parent);
			}
		}

		return parent;
	}

	@Override
	public List<Permission> listUserPermissionByUid(String uid) {

		return baseMapper.selectUserPermissionByUid(uid);
	}

	@Override
	public List<String> listUserPermissionCodeByUid(String uid) {
		return baseMapper.selectUserPermissionCodeByUid(uid);
	}

}
